<?php

namespace App\Models;

class GoodsPicPrimaryViewModel extends ToyModel
{
    protected $table = 'pic_primary_all';

    protected $guarded = [];

    /**
     * 获取商品列表
     * @param $request
     * @return mixed
     */
    public static function getModel($request): mixed
    {
        $Model = self::where('PStatus', 0)->where('PID', 0);
        $Model = GoodsPicPrimaryModel::getQueryModel($Model, $request);
        if ($request->input('area_id'))
            $Model = $Model->whereIn('AreaID', self::getAreaMapRelation(intval($request->input('area_id'))));
        if ($request->input('tag'))
            $Model = $Model->where('Type', 'like', '%|'. $request->input('tag') . '|%');
        if ($request->input('type')) {
            $field = self::getQueryField(intval($request->input('area_id', 1)), intval($request->input('type')));
            $order = self::getOrderField(intval($request->input('area_id', 1)), intval($request->input('type')));
            if ($field)
                $Model = $Model->where($field, 1);
            $Model = $Model->orderByDesc($order);
        }
        return $Model;
    }

    /**
     * 获取地区查询条件
     * @param int $area_id
     * @return array
     */
    public static function getAreaMapRelation(int $area_id = 1): array
    {
        return match ($area_id) {
            1 => [1, 3, 4],
            2 => [2, 3],
            3 => [3, 4],
            default => [$area_id],
        };
    }

    /**
     * 获取查询字段
     * @param int $area_id
     * @param int $type
     * @return string
     */
    public static function getQueryField(int $area_id = 1, int $type = 1): string
    {
        if ($type === 4)
            return 'IsB';
        if ($type >= 5)
            return '';
        if ($area_id === 1)
            return ['', 'IsRecommend', 'IsNew', 'IsRight'][$type];
        if ($area_id === 2)
            return  ['', 'IsRecommend1', 'IsNew1', 'IsRight'][$type];
        if ($area_id === 3 || $area_id === 4)
            return  ['', 'IsRecommend2', 'IsNew2', 'IsRight'][$type];
        return '';
    }

    /**
     * 获取排序字段
     * @param $area_id
     * @param $type
     * @return string
     */
    public static function getOrderField($area_id, $type): string
    {
        if ($type >= 4)
            return 'ITime';
        if ($area_id === 1)
            return ['ITime', 'RecommendID', 'NewID', 'RightID'][$type];
        if ($area_id === 2)
            return  ['ITime', 'RecommendID1', 'NewID1', 'RightID1'][$type];
        if ($area_id === 3 || $area_id === 4)
            return  ['ITime', 'RecommendID2', 'NewID2', 'RightID2'][$type];
        return 'ITime';
    }
}
